package github.ziwukun.jsonql.orm;

import com.fasterxml.jackson.annotation.JsonAlias;

import lombok.Data;

/**
 * 外键链接的模型
 * @author Hugo.Yu
 */
@Data
class FmPropBuilder {
	// 作为外部模型的属性名称
	@JsonAlias({"prop","propName"})
	String propName;
	// 是否是单一数量 是否只有一个
	@JsonAlias({"one","single"})
	boolean single = true;
	// 模型定义
	@JsonAlias({"model"})
	ModelBuilder model;
	
	// 外键*属性*名，不是字段名称
	@JsonAlias({"fm-prop","fmProp"})
	String fmProp;
	// 持有外键属性的*模型*名称
	@JsonAlias({"mapped-by","mappedBy"})
	String mappedBy;
	
	FmPropImpl toFmProp(ModelImpl ofModel) {
		return new FmPropImpl(this,ofModel);
	}
	
	FmContainerImpl toFmCtn(ContainerImpl ctn,CtnFieldImpl fmField,
		ContainerImpl mappedBy) {
		return new FmContainerImpl(ctn, fmField, mappedBy);
	}
	
	public static void instanceFmProp(FmPropBuilder builder,FmPropImpl fmProp
		,ModelImpl ofModel) {
		OrmAssert.notBlank(builder.propName, "属性名称不能为空");
		OrmAssert.notBlank(builder.fmProp, "外键字段不能为空");
		OrmAssert.notBlank(builder.mappedBy, "mappedBy不能为空");
		
		fmProp.propName = builder.propName;
		fmProp.single = builder.single;
		fmProp.ofModel = ofModel;
		fmProp.propModel = builder.model.toModel();
		
		Model mappedBy = null;
		if(builder.mappedBy.equals(ofModel.modelName)) {
			if(!fmProp.single) {
				throw new OrmException("mappedBy参数{}和single参数冲突",builder.mappedBy);
			}
			mappedBy = ofModel;
		}
		else if(builder.mappedBy.equals(fmProp.propModel.modelName)) {
			mappedBy = fmProp.propModel;
		}
		else {
			throw new OrmException("无效的mappedBy参数{}",builder.mappedBy);
		}
		Prop prop = mappedBy.getPropByName(builder.fmProp);
		if(prop == null) {
			throw new OrmException("无效的fmProp参数{}",builder.fmProp);
		}
		if(!(prop instanceof CtnProp)) {
			throw new OrmException("无效的fmProp参数{},类型错误",builder.fmProp);
		}
		fmProp.fmProp = (CtnProp) prop;
	}
}
